package com.davidlife.javase.netsocket.uploadfiles;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpUploadServer {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(8888);

        File uploadPath = new File("upload");
        if (!uploadPath.exists()) {
            uploadPath.mkdirs();
        }
        System.out.println("服务器已启动，等待连接。。。");

        while (true) {
            Socket s = ss.accept();
            InputStream is = s.getInputStream();

            BufferedInputStream bis = new BufferedInputStream(is);
            String fileName = uploadPath + "\\file" + System.currentTimeMillis() + ".png";
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileName));
            byte[] b = new byte[1024 * 8];
            int len;
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            bos.flush();
            System.out.println("已将上传文件保存在：" + fileName);

            OutputStream os = s.getOutputStream();
            os.write("上传成功".getBytes());
            os.close();

            bos.close();
            bis.close();
            s.close();
        }
    }
}
